<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="李修倩在 Github 上的个人博客">
    <meta name="keyword" content="null">
    <meta name="theme-color" content="#600090">
    <meta name="msapplication-navbutton-color" content="#600090">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="#600090">
    <link rel="shortcut icon" href="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-person-128.png">
    <link rel="alternate" type="application/atom+xml" title="Xiuqianli&#39;s blog" href="/atom.xml">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.css">
    <title>
        
        JVM类加载简单笔记｜xiuqianli&#39;s blog
        
    </title>

    <link rel="canonical" href="https://981764793.gitee.io/2018/07/18/JVM类加载简单笔记/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/blog-style.css">

    <!-- Pygments Github CSS -->
    <link rel="stylesheet" href="/css/syntax.css">
</head>

<style>

    header.intro-header {
        background-image: url('http://oco8bvfr8.qnssl.com/blog-bg-black-run.jpg?imageView2/1/w/1400/h/400/interlace/1/q/80')
    }
</style>
<!-- hack iOS CSS :active style -->
<body ontouchstart="" class="animated fadeIn">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top " id="nav-top" data-ispost = "true" data-istags="false
" data-ishome = "false" >
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand animated pulse" href="/">
                <span class="brand-logo">
                    Xiuqianli&#39;s blog
                </span>
                's Blog
            </a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <!-- /.navbar-collapse -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/">Home</a>
                    </li>
					
                    
                        
							
                        <li>
                            <a href="/Tags/">Tags</a>
                        </li>
							
						
                    
					
					
                </ul>
            </div>
        </div>
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
//    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>

<!-- Main Content -->

<!--only post-->


<img class="wechat-title-img"
     src="http://oco8bvfr8.qnssl.com/blog-bg-black-run.jpg?imageView2/1/w/1400/h/400/interlace/1/q/80">


<style>
    
    header.intro-header {
        background-image: url('http://oco8bvfr8.qnssl.com/blog-bg-black-run.jpg?imageView2/1/w/1400/h/400/interlace/1/q/80')
    }

    
</style>

<header class="intro-header">
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <div class="post-heading">
                    <h1>JVM类加载简单笔记</h1>
                    
                    <span class="meta">
                         作者 Xiuqian Li
                        <span>
                          日期 2018-07-18
                         </span>
                    </span>
                    <div class="tags text-center">
                        
                        <a class="tag" href="/tags/#java"
                           title="java">java</a>
                        
                        <a class="tag" href="/tags/#jvm"
                           title="jvm">jvm</a>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="post-title-haojen">
        <span>
            JVM类加载简单笔记
        </span>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">
            <!-- Post Container -->
            <div class="col-lg-8 col-lg-offset-1 col-sm-9 post-container">
                <h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><p>只是自己简单理解后看完相关内容后为加强记忆敲的一个笔记，不一定完全正确。原文<a href="http://www.cnblogs.com/xrq730/p/4844915.html" target="_blank" rel="noopener">Java虚拟机9：Java类加载机制</a></p>
<h4 id="类加载机制"><a href="#类加载机制" class="headerlink" title="类加载机制"></a>类加载机制</h4><p>类加载总共有7个步骤：加载(Loading)、验证（Verification）、准备(Preparation)、解析(Resolution)、初始化(Initiallization)、使用(Using)、卸载(Unloading)。其中验证、准备、解析三步可并称为连接（Linking）。</p>
<p>加载、验证、准备、初始化、卸载5个步骤是确定的，使用不用多说，加载完了就可以用了呗，解析是为了实现java的动态绑定（运行时绑定）这一特性，某些情况下可以放在初始化阶段之后再完成。</p>
<h5 id="加载"><a href="#加载" class="headerlink" title="加载"></a>加载</h5><p>java的类加载器基于双亲委派模型实现，在jdk 1.2之后引入。</p>
<p>双亲委派模型简述：有父加载器通过父加载器加载，否则尝试从启动类加载器（BootstrapClassLoader）加载，如果这两都没加载成功的话再从当前类加载器加载。</p>
<p>双亲委派模型的作用：最基本的作用，安全，可以防止黑客入侵后可以注入恶意的基础类。</p>
<p>加载分为预加载和运行时加载。</p>
<p>1.预加载：加载的是JAVA_HOME/lib/rt.jar，这个jar包里是jdk常用的类，例如：java.io.*、java.uitil.*、java.lang.*,这些是一些最常用的类，所以在虚拟机启动时就加载。</p>
<p>2.运行时加载：指程序运行时需要用到某个class，先在内存中查找这个class，没有的话就根据这个class的全限定名进行加载。</p>
<p>加载过程：</p>
<p>1.获取class文件的字节流<br>2.将类信息、字节码、常量、静态变量这些class文件中的内容放到方法区<br>3.在内存中生成一个java.lang.Class对象，作为方法去中这个class的各种信息的访问接口。一般这个对象存放在堆中。</p>
<p>虚拟机并没有对第一步的获取字节流进行限制，可以通过各种途径获取class的字节流进行类加载，比如压缩包（war包），网络数据(applet)，动态生成(动态代理，asm框架)，其他文件编译（jsp）等</p>
<h5 id="验证"><a href="#验证" class="headerlink" title="验证"></a>验证</h5><p>这一阶段的主要目的是验证class内容符合当前虚拟机环境且不会危害到虚拟机自身的安全。</p>
<p>最主要的就是验证class文件格式是否正确，不能随便一个字节流都能往虚拟机里加载，保证安全。</p>
<p>其次就是验证编译class的jdk版本，保证高版本jdk能向下兼容，但是低版本不能向上兼容，例如：jdk1.6编译的class能在jdk1.7、jdk1.8的环境运行，但是不能在jdk1.5环境下运行，如果尝试在低版本环境加载高版本编译的类会报java.lang.UnsupportedClassVersionError异常。</p>
<p>其他的还有元数据验证、字节码验证、符号引用验证</p>
<h5 id="准备"><a href="#准备" class="headerlink" title="准备"></a>准备</h5><p>准备阶段就是给类变量（static修饰的静态变量）分配空间并赋零值（初始值），为静态变量初始化做准备。内存空间都是划分在方法区。</p>
<p>1.只有类变量才会进行分配空间赋初始值，成员变量（实例变量）会在类实例化的时候进行分配空间赋值，随类实例划分在java堆中</p>
<p>2.没有final修饰的静态变量才会赋零值，final修饰的静态常量会直接进行复制，例如static int i = 12，准备阶段结束后i的值是0，但是static final int i = 12在准备阶段结束后i的值就是12.</p>
<h5 id="解析"><a href="#解析" class="headerlink" title="解析"></a>解析</h5><p>解析阶段的工作就是将符号引用解析（替换）成直接引用。</p>
<p>符号引用是指变量类型、变量名等信息，与内存布局无关。</p>
<p>直接引用可以是直接指向目标变量的指针、相对偏移量、能间接定位到目标的句柄等能够直接在内存中找到目标的信息。</p>
<h5 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h5><p>初始化阶段干的事就是给静态变量赋指定的值，执行静态方法块。虚拟机会保证多线程环境下类初始化被正确的加锁、同步，即多线程同时初始化一个类时只有一个线程会进行类初始化操作。</p>
<h4 id="类加载器"><a href="#类加载器" class="headerlink" title="类加载器"></a>类加载器</h4><p>类加载器在虚拟机的角度来看分为两种：启动类加载器和其他类加载器。启动类加载器由c++实现，是虚拟机的一部分，其他类加载器由java实现，独立于虚拟机之外，全部继承于java.lang.ClassLoader</p>
<p>在程序员角度来看可以分得更细致：启动类加载器、扩展类加载器、应用程序加载器、自定义加载器等。</p>
<p>只有在两个类都是由同一个类加载器加载的情况下才能判断是否相等，不然永远是不相等。包括代表类的.class对象的equals()方法、isAssignableFrom()方法、isInstance()方法的返回结果，也包括使用instanceof关键字做对象所属关系判定等情况。</p>

                <hr>
                

                <ul class="pager">
                    
                    <li class="previous">
                        <a href="/2018/07/28/手写山寨spring基础功能-JDBC/" data-toggle="tooltip" data-placement="top"
                           title="手写山寨spring基础功能 - JDBC">&larr; Previous Post</a>
                    </li>
                    
                    
                    <li class="next">
                        <a href="/2018/07/18/ThreadLocal源码泛读笔记/" data-toggle="tooltip" data-placement="top"
                           title="ThreadLocal源码泛读笔记">Next Post &rarr;</a>
                    </li>
                    
                </ul>

                

                


                <!--加入新的评论系统-->
                
            </div>

            <div class="hidden-xs col-sm-3 toc-col">
                <div class="toc-wrap">
                    <ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#前言"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#类加载机制"><span class="toc-text">类加载机制</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#加载"><span class="toc-text">加载</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#验证"><span class="toc-text">验证</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#准备"><span class="toc-text">准备</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#解析"><span class="toc-text">解析</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#初始化"><span class="toc-text">初始化</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#类加载器"><span class="toc-text">类加载器</span></a></li></ol>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5 class="text-center">
                        <a href="/tags/">FEATURED TAGS</a>
                    </h5>
                    <div class="tags">
                        
                        <a class="tag" href="/tags/#java"
                           title="java">java</a>
                        
                        <a class="tag" href="/tags/#jvm"
                           title="jvm">jvm</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
            </div>
        </div>

    </div>
</article>







<!-- Footer -->
<!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1 text-center">
                <br>
                <ul class="list-inline text-center">
                
                
                
                    <li>
                        <a target="_blank" href="https://www.zhihu.com/people/asdf1234-97">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa  fa-stack-1x fa-inverse">知</i>
                            </span>
                        </a>
                    </li>
                

                

                

                
                    <li>
                        <a target="_blank"  href="https://github.com/xiuqianli1996">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; Xiuqianli&#39;s blog 2018
                    <br>
                    <span id="busuanzi_container_site_pv" style="font-size: 12px;">PV: <span id="busuanzi_value_site_pv"></span> Times</span>
                    <br>
                    Theme by <a href="https://haojen.github.io/">Haojen Ma</a>
                </p>

            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/js/blog.js"></script>

<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("https://981764793.gitee.io/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("//cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>

<!-- Google Analytics -->



<!-- Baidu Tongji -->


<!-- swiftype -->
<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
  (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
  e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install','null','2.0.0');
</script>

<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<!--wechat title img-->
<img class="wechat-title-img" src="null">
</body>

</html>
